/**
 * 定义一个require模块，并依赖app模块
 */
define(["app", "popup/popup-jpress", "util/current-tab"], function(app, jpress, currentTab) {

    /*
    platform = {
        "valid":true,
        "reason":"",
        "nickname":"N小聪",
        "platformName":"jianshu",
        "userId":"20451298",
        "platformDisplayName":"简书"
    }
     */
    var platform;


    var init = function(item, plat){
        platform = plat;
        item.bind("click", showMenu);
        // 无效时检测是否在简书界面中
        platform.valid || detect();
    }

    var showMenu = function(){
        if(!platform || !platform.valid){
            $.actions({
                title : platform.reason,
                actions: [{
                    text: "打开" + platform.platformDisplayName + "设置",
                    onClick: function(){
                        $.alert("请在新打开的窗口<br/>登陆CSDN博客后重新打开插件", "", goLoginPage);
                    }
                }]
            });
        } else {
            $.toptip("配置正常", 1000, "success")
        }
    }

    var detect = function(){
        if(currentTab.domain !== "i.csdn.net"){
            return;
        }
        // 调用api查询当前页面对应的cookie
        chrome.cookies.getAll({
            "domain" : ".csdn.net"
        }, function(cookies){
            // console.log("简书cookie-init：" + JSON.stringify(cookies));
            var username
            var usertoken
            for(var i in cookies){
                var cookie = cookies[i];
                if(cookie.name === "UserName"){
                    username = cookie.value;
                } else if(cookie.name === "UserToken"){
                    usertoken = cookie.value;
                }
            }
            if(!usertoken || !username){
                return;
            }
            console.log("popup-csdn.js [detect] - cookie[username]=" + username + ", cookie[usertoken]=" + usertoken);

            // 查询用户
            app.ajaxGet("https://me.csdn.net/api/user/show", {cookie: cookies})
                .done(function(userResp, a){
                    //{ "code": 200, "message": "成功", "data": { "birthday": "", "country": 0, "gender": 1, "genderStr": "男", "city": 0, "avatarurl": "https://profile.csdnimg.cn/2/6/B/1_weixin_40706188", "lastupdatedate": "2020-01-10 14:01:27", "teamsize": null, "companyintro": "", "selfdesc": "", "workstartdate": "", "updateNicknameDate": "2020-02-08 16:04:40", "years": 2, "edudegree": null, "province": 0, "hukou": "", "cityStr": "", "maritalstatusStr": "", "nickname": "N小聪的二度世界", "ethnicStr": "", "provinceStr": "", "countryStr": "", "ethnic": null, "industrytype": 0, "nextupnickspan": 0, "csdnid": 70688214, "curcompany": "", "curjob": "", "gradschool": "", "qrcodeattachurl": "", "realname": "", "registerurl": "https://g.csdnimg.cn/static/user-reg-year/1x/2.png", "loginemail": "nianzecong@aliyun.com", "maritalstatus": null, "district": null, "edudegreeStr": "", "days": 813, "selfdomain": "", "card": "", "username": "weixin_40706188", "homepage": [], "industry_name": "", "address": "" } }
                    console.log("CSDN用户：" + JSON.stringify(userResp))
                    if(!userResp || !userResp.data){
                        $.alert("查询用户信息失败", "数据异常")
                        return;
                    }
                    dologin({
                        username : username,
                        usertoken : usertoken,
                        nickname : userResp.data.nickname
                    })
                }).fail(function(e){
                    $.alert(JSON.stringify(e), "系统异常");
                })
        });
    }

    var goLoginPage = function(){
        // https://mp.toutiao.com/auth/page/login/?hideThird=true
        chrome.tabs.create({'url': 'https://i.csdn.net'});
    }


    /**
     * 用当前页面配置信息登陆
     * @param conf = {
            username : "xxxxx",
            usertoken : "xxxxx",
            nickname : "xxxx"
        }
     */
    var dologin = function(conf){
        $.confirm("是否保存名为<br/>" + conf.nickname + "（" + conf.username + "）<br/>的CSDN账号", "", function() {
            doSaveConfig(conf.username, conf.usertoken, true);
        })
    }

    // 保存配置到插件后台
    var doSaveConfig = function(username, usertoken, draftOnly){
        var config = {
            enable : true,
            username : username,
            cookie : "UserToken=" + usertoken + ";"
        }
        console.log("popup-csdn.js [doSaveConfig] - " + JSON.stringify(config));
        // 保存内容
        jpress.doSavePlatform(platform.platformName, config)
    }


    /**
     * 向外暴露方法
     */
    return {
        init : init
    }
})